<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <!-- 导航 -->
        <el-row>
          <!-- 导航左侧 -->
          <el-col :span="12">
            <el-form ref="subjectFrom" :model="queryList" label-width="80px">
              <el-form-item label="目录名称">
                <el-input v-model="queryList.tagName" class="inputCol" />
              </el-form-item>
              <el-form-item label="状态">
                <el-select v-model="queryList.state" placeholder="请选择">
                  <el-option label="已启用" :value="1" />
                  <el-option label="已禁用" :value="0" />
                </el-select>
              </el-form-item>
              <!-- <el-col class="left-fot"> -->
              <span style="margin-left: 10px">
                <el-button
                  size="small"
                  class="colInput"
                  plain
                  @click="resetInput"
                  >清除</el-button
                >
                <el-button
                  size="small"
                  class="colInput"
                  type="primary"
                  @click="listFn"
                  >搜索</el-button
                >
              </span>

              <!-- </el-col> -->
            </el-form>
          </el-col>
          <!-- 导航右侧 -->
          <el-col :span="12">
            <el-button
              style="margin-left: 85%"
              size="small"
              type="success"
              @click="addDialogVisible = true"
            >
              <i class="el-icon-edit"></i>
              <span>新增标签</span>
            </el-button>
          </el-col>
        </el-row>
        <!-- 消息-->
        <el-row>
          <el-alert
            :title="`数据一共 ${counts} 条`"
            type="info"
            show-icon
            :closable="false"
          >
          </el-alert>
        </el-row>
        <!-- 表格 -->
        <el-row>
          <!-- 表格区域 -->
          <el-table :data="tagList" style="width: 100%">
            <el-table-column type="index" label="序号" />
            <el-table-column prop="subjectName" label="所属学科" />
            <el-table-column prop="tagName" label="目录名称" />
            <el-table-column prop="username" label="创建者" />
            <el-table-column prop="addDate" label="创建日期">
              <template v-slot="scope">
                <span>{{ scope.row.addDate | formatTime }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="state" label="状态">
              <template slot-scope="scope">
                {{ scope.row.state === 1 ? "已启用" : "已禁用" }}
              </template>
            </el-table-column>
            <el-table-column prop="address" label="操作">
              <template slot-scope="scope">
                <el-button type="text" @click="editState(scope.row)">{{
                  scope.row.state === 1 ? "禁用" : "启用"
                }}</el-button>
                <el-button
                  type="text"
                  :disabled="scope.row.state === 1"
                  @click="editTags(scope.row)"
                  >修改</el-button
                >
                <el-button
                  type="text"
                  :disabled="scope.row.state === 1"
                  @click="removeTag(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-row>
        <!-- 分页 -->
        <el-row>
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryList.page"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="queryList.pagesize"
            layout="prev, pager, next, sizes, jumper"
            :total="counts"
          >
          </el-pagination>
        </el-row>
      </el-card>

      <!-- 修改标签弹框 -->
      <el-dialog
        title="修改标签"
        :visible.sync="editDialogVisible"
        width="20%"
        @close="restDir"
      >
        <!-- 主体区域 -->

        <el-form
          ref="tagsFormRef"
          :model="editTagList"
          :rules="tagsFormRules"
          label-width="80px"
          class="demo-ruleForm"
        >
          <el-row>
            <el-col :span="24">
              <el-form-item
                v-if="!subjects.id && !subjects.name"
                class="elform"
                label="所属学科"
                :required="true"
              >
                <el-select
                  v-model="editTagList.value"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in addFrom"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item
                class="elform"
                label="目录名称"
                prop="tagName"
              >
                <el-input
                  v-model="editTagList.tagName"
                  placeholder="请输入目录名称"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editTagsForm">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 添加标签弹框 -->
      <el-dialog
        title="新增标签"
        :visible.sync="addDialogVisible"
        width="20%"
        @close="restDir"
      >
        <el-row>
          <el-col>
            <el-form
              ref="tagsFormRef"
              :model="tagsForm"
              :rules="tagsFormRules"
              label-width="80px"
              class="demo-ruleForm"
            >
              <el-form-item
                v-if="!subjects.id && !subjects.name"
                class="elform"
                label="所属学科"
                :required="true"
              >
                <el-select
                  v-model="tagsForm.value"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in addFrom"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                class="elform"
                label="目录名称"
                prop="tagName"
              >
                <el-input
                  v-model="tagsForm.tagName"
                  placeholder="请输入目录名称"
                  style="width: 100%"
                />
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addTagsForm">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { list, changeState, remove, update, add } from '../../api/hmmm/tags'
import { simple } from '../../api/hmmm/subjects'
import dayjs from 'dayjs'
export default {
  name: 'zifuchuan',
  // 过滤器
  filters: {
    // 格式化日期
    formatTime (time) {
      return dayjs(time).format('YYYY-MM-DD hh:mm:ss')
    }
  },

  data () {
    return {
      infoId: '',
      tagList: [], // 从接口处取回
      counts: 0, // 总条数
      subjectID: 0,
      // 请求的参数
      queryList: {
        page: 1,
        pagesize: 10,
        tagName: '',
        state: null
      },

      // 修改请求数据
      editTagList: {
        tagName: '',
        value: ''
      },

      // 简单数据列表
      addFrom: [],

      // 添加标签数据
      tagsForm: {
        tagName: '',
        // 下拉框的值
        value: ''
      },

      // 修改的弹框
      editDialogVisible: false,

      // 验证
      tagsFormRules: {
        tagName: [
          { required: true, message: '请输入目录名称', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ]
      },

      showDialog: false, // 控制新增标签的弹框隐藏展示

      // 添加标签的弹框
      addDialogVisible: false
    }
  },

  watch: {
    '$route.query' () {
      this.listFn()
    }
  },

  created () {
    this.listFn()
    this.getAddFrom()
    console.log(this.addFrom)
  },

  // 获取地址栏数据
  computed: {
    subjects () {
      return this.$route.query || null
    }
  },

  methods: {
    // 切换状态
    async editState (row) {
      console.log(row)
      try {
        await changeState({
          id: row.id,
          state: row.state === 1 ? 0 : 1
        })
        this.$message.success('操作成功')
        row.state = row.state === 1 ? 0 : 1
      } catch (e) {
        this.$message.error('请求错误!')
      }
    },

    // 删除
    async removeTag (row) {
      const configRuselt = await this.$confirm(
        '此操作将永久删除该学科, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (configRuselt !== 'confirm') {
        return this.$message('您取消了删除操作!')
      }
      try {
        const { data } = await remove(row)
        console.log(data)
        this.$message.success('删除成功!')
        this.listFn()
      } catch (e) {
        this.$message.error('删除失败!')
      }

      // 如果分页只剩一条数据
      if (this.tagList.length === 1) {
        // 让页面减一
        this.queryList.page--
        // 如果第一页只剩一条数据，删除以后，让 page 还原为 1
        if (this.queryList.page <= 0) {
          this.queryList.page = 1
        }
      }
    },

    // 添加
    async addTagsForm () {
      try {
        if (this.subjects.id && this.subjects.name) {
          await add({
            subjectID: +this.subjects.id,
            tagName: this.tagsForm.tagName
          })
          this.$message.success('新增标签成功')
          this.addDialogVisible = false
          this.listFn()
        } else {
          await add({
            subjectID: this.tagsForm.value,
            tagName: this.tagsForm.tagName
          })
          this.$message.success('新增标签成功')
          this.addDialogVisible = false
          this.listFn()
        }
      } catch (e) {
        this.$message.error('新增标签失败')
        console.log(e)
      }
    },

    // 修改
    async editTagsForm () {
      try {
        if (this.subjects.id && this.subjects.name) {
          await update({
            id: this.infoId,
            subjectID: this.subjectID,
            tagName: this.editTagList.tagName
          })
          console.log(this.infoId)
          console.log(this.subjects.id)
          this.$message.success('修改目录成功')
          this.editDialogVisible = false
          this.listFn()
        } else {
          await update({
            id: this.infoId,
            subjectID: this.subjectID,
            tagName: this.editTagList.tagName
          })
          this.$message.success('修改目录成功')
          this.editDialogVisible = false
          this.listFn()
        }
      } catch (e) {
        console.log(e)
      }
    },

    // 重置表单
    restDir () {
      this.$refs.tagsFormRef.resetFields()
      this.tagsForm.value = ''
    },

    // // 重新渲染列表，隐藏弹框
    // updateList () {
    //   this.showDialog = false
    //   this.listFn()
    // },

    // 点击修改显示弹框
    editTags (row) {
      this.editTagList.value = row.subjectID
      // console.log(row.subjectName)
      console.log(row)
      this.subjectID = row.subjectID
      this.infoId = row.id
      this.subjectID = row.subjectID
      this.editTagList.tagName = row.tagName
      console.log(this.infoId)
      console.log(this.editTagList.tagName)
      this.editDialogVisible = true
    },

    // 获取学科列表
    async getAddFrom () {
      const res = await simple()
      this.addFrom = res.data
    },

    // 清除数据
    resetInput () {
      this.queryList.tagName = ''
      this.queryList.state = null
      this.listFn()
    },

    // 获取标签列表
    async listFn () {
      const res = await list(this.queryList)
      this.tagList = res.data.items
      this.counts = res.data.counts
      console.log(res)
    },

    // 每页显示的条数发生改变时触发
    handleSizeChange (newSize) {
      this.queryList.pagesize = newSize
      // console.log(newSize)
      // console.log(this.query.pagesize)
      this.listFn()
    },

    // 当前页面发生改变时触发
    handleCurrentChange (newPage) {
      console.log(newPage)
      this.queryList.page = newPage
      this.listFn()
    }
  }
}
</script>

<style scoped lang="scss">
// .left-fot {
//   margin-left: 9px;
// }
.el-row {
  margin-top: 20px;
}
.colInput {
  height: 35px;
}
.colright {
  float: right;
  height: 35px;
  margin-left: 10px;
}
.el-breadcrumb {
  padding-bottom: 20px;
  border-bottom: 1px solid #ccc;
}
.inputCol {
  width: 200px;
}
.el-form-item {
  display: inline-block;
}
.el-table {
  margin-top: 10px;
}
.el-pagination {
  float: right;
  margin-top: 20px;
}
.elform {
  width: 100%;
}

.el-form-item__content {
  margin-left: 10px;
}
</style>
